package com.lijinjiang.view;

import com.lijinjiang.listener.MyKeyCall;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
 * 自定义用户框类
 */
public class MyComboBox<E> extends JComboBox<E> {
    private static final long serialVersionUID = -5644130161720236522L;

    // 自定义遮罩层
    JLabel mask = new JLabel();

    /* 默认显示值 */
    public void setPlaceholder(String text) {
        Rectangle bs = this.getBounds();
        mask.setText(text);
        mask.setForeground(Color.lightGray);
        mask.setBounds(2, 0, bs.width - 2, bs.height - 2);
        mask.setFont(new java.awt.Font("宋体", 0, 12));
        this.getEditor().getEditorComponent().addFocusListener(focusThere);
        this.add(mask);
    }

    // 添加焦点监听器，监听输入动作
    FocusListener focusThere = new FocusListener() {
        public void focusGained(FocusEvent e) {
            mask.setVisible(false);
        }

        public void focusLost(FocusEvent e) {
            JTextField textField = (JTextField) e.getComponent();
            String text = textField.getText();
            if (text == null || text.length() == 0) {
                mask.setVisible(true);
            }
        }
    };


    /* 键盘监听 */
    private MyKeyCall call;

    KeyAdapter adapter = new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
            call.callBack(e);
        }
    };

    /* 键盘监听 */
    public void keyPressedCall(MyKeyCall call) {
        this.call = call;
        addKeyListener(adapter);
    }
}
